<template>
  <div style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)" >
    <div style="border: 2px solid #409EFF;border-top:none;border-left:none;border-right:none; margin-bottom:20px;"> 
      <div style="margin-top:10px;padding-bottom:15px; padding-top:15px;background:white">
          <el-row type="flex" justify="center">
            <el-col :span="6" >
              <el-button @click="addUserDialog" icon="el-icon-search" v-show="showSearch" size="small" type="success" round >添加员工</el-button>          
            </el-col>        
            <el-col :span="6"  :offset="2">
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-col>

          </el-row>  
      </div>
    </div>
    <div>
      <el-row :gutter="50">
        <el-col :span="6" :offset="1" style="padding-right:20px;">
          <el-input
            placeholder="输入部门关键字进行过滤"
            v-model="filterText"
            >
          </el-input>
          <el-tree
            class="filter-tree"
            :data="departmentData"
            :props="defaultProps"
            default-expand-all
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
            ref="tree">
          </el-tree>          
        </el-col>
        <el-col :span="16">
          <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="用户名" align="center" :show-overflow-tooltip="true" v-if="columns[0].visible">
              <template slot-scope="scope">
                <div>{{ scope.row.username }}</div>
              </template>
            </el-table-column>
            <el-table-column label="用户姓名" align="center" :show-overflow-tooltip="true" v-if="columns[1].visible">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <p>用户姓名: {{ scope.row.personName }}</p>
                  <div slot="reference" class="name-wrapper">
                    <el-tag size="medium">{{ scope.row.personName }}</el-tag>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="部门" align="center" :show-overflow-tooltip="true" v-if="columns[2].visible">
              <template slot-scope="scope" >
                <div >{{
                  scope.row.departmentName
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="用户状态" align="center" :show-overflow-tooltip="true" v-if="columns[3].visible">
              <template slot-scope="scope">
                <!-- <p v-if="scope.row.states===0">可用</p>
                <p v-else>不可用</p> -->
              <el-switch
                v-model="scope.row.states"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
              </template>
            </el-table-column>   
            <el-table-column label="操作" >
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteUser(scope.row.departmentId)">删除</el-button>          
              </template>
            </el-table-column>
          </el-table>          
        </el-col>
      </el-row>
    </div>
    <div>
    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="addUserVisible" width="600px" append-to-body>
      <el-form ref="formAddUser" :model="formAddUser" :rules="formAddUserRules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="formAddUser.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect v-model="formAddUser.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="请选择员工部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="personName">
              <el-autocomplete
                v-model="formAddUser.personName"
                :trigger-on-focus="false"
                :fetch-suggestions="queryUserByUsername"
                placeholder="请输入员工姓名"
                @select="handleSelect"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveUser">确 定</el-button>
        <el-button @click="addUserVisible=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>

  <div>
    <el-dialog title="部门员工管理"  :visible.sync="departmentUserVisible"  :close-on-click-modal="false" center  >
        <el-table ref="multipleTable" :data="departmentUserTableData" style="width: 100%" >
        <el-table-column type="selection" width="55" ></el-table-column>
        <el-table-column label="用户名" width="150">
          <template slot-scope="scope">
            <div>{{ scope.row.username }}</div>
          </template>
        </el-table-column>
        <el-table-column label="用户姓名" width="150">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>用户姓名: {{ scope.row.personName }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.personName }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="用户状态" width="150">
          <template slot-scope="scope">
            <!-- <p v-if="scope.row.states===0">可用</p>
            <p v-else>不可用</p> -->
          <el-switch
            v-model="scope.row.states"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="用户创建时间" width="180">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{$moment(scope.row.createTime).format('YYYY-MM-DD')}}</span>
          </template>
        </el-table-column>      
        <!-- <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click="checkUser(scope.row.userId)">查看</el-button>                            
          </template>
        </el-table-column> -->
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="departmentUserVisible = false">取 消</el-button>
        <el-button size="small" type="primary" >确 定</el-button>
      </div>
    </el-dialog>
  </div>

    <!--prev表示上一页，next为下一页，pager表示页码列表,total表示总条目数，size用于设置每页显示的页码数量。-->
    <el-pagination
      background
      layout="total,prev,sizes, pager, next,jumper"
      :total="total"
      :page-sizes="[5, 10, 15, 20]"
      :page-size.sync="formSearch.pageSize"
      :current-page.sync="formSearch.pageNum"
      @current-change="getPage"
      @size-change="getPage"
      style="float: right">
    </el-pagination>
  </div>
</template>

<script>
import dept from '../../../api/department.js';
import user from '../../../api/user.js';
import log from '../../../api/log.js';
import Treeselect from "@riophae/vue-treeselect";
import RightToolbar from "../../../components/RightToolbar/index"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "List",
  components: { Treeselect ,RightToolbar},
  data() {
    return {
      tableData: [],
      total:0,//记录数,
      formSearch:{
        pageNum:1,//当前页
        pageSize:10,//每页记录数
        departmentId:''
      },
      //添加部门
      formAddUserRules: {
        parentId: [{required:true, message:"请选择用户部门",trigger:'blur'}],
        personName: [{required:true, message:"请输入用户名称",trigger:'blur'}],        
      },
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      addUserVisible: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        departmentName: undefined,
      },
      // 表单参数
      formAddUser: {},
      //查询
      queryCustomer:{
        pageNum:1,//当前页
        pageSize:5,//每页记录数        
        departmentName:'',
        customerType:''
      },
      //批量删除ids
      customerIdsArray:[],
      customerIds:'',
      //导出
      exportCustomerUrl:'',
      //部门员工管理
      departmentUserVisible:false,
      departmentUserTableData:{},

      departmentData:[],
      filterText: '',
      //部门树
      defaultProps: {
        id:'departmentId',
        children: 'children',
        label: 'departmentName'
      },
      // 查询参数
      queryParams: {
        departmentName: undefined,
      },
      // 显示搜索条件
      showSearch: true,
      // 列信息
      columns: [
        { key: 0, label: `用户名`, visible: true },
        { key: 1, label: `用户姓名`, visible: true },
        { key: 2, label: `类型`, visible: true },
        { key: 3, label: `用户状态`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `邮箱`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      //下拉搜索用户名称模糊搜索
      restaurants: [],
      state: {
        username:'',
        personName:'',
        userId:''
      },
      timeout:  null,
    }        
  }  ,  

  created(){
    this.getPage()
    this.getList();
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  }, 
  methods: {
    //分页
    /*
1）await只能在async函数内部使用：不能放在普通函数里面，否则会报错；
2）await关键字后面跟Promise对象：在Pending状态时，相应的协程会交出控制权，进入等待状态，这是协程的本质；不加 return
3）await是async wait的意思：
    */
    async getPage(){
      const res=await dept.departmentByUser(this.formSearch);
      if(res.data.code ==='000'){
          this.tableData=res.data.data.records;
          this.total=res.data.data.total;
      }
    },
    //删除指定员工
    async deleteUser(departmentId){
      this.$confirm("确定删除这条部门信息么","提示",{
        confirmButtonText:'确定',
        cancelButtonText:'取消'
      }).then(()=>{
        dept.delCustomer({departmentId:departmentId}).then(res =>{
          console.log(res);
          if(res.data.code ==='000'){
            this.getPage(),
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          }else{
            this.$message.error('删除失败');    
          }
        })
      }).catch()
    },
    //新增客户弹出框
    async addUserDialog(){
      try {
        this.$refs['formAddUser'].resetFields()
      } catch (err) {
      }
      this.addUserVisible=true;
      this.title = "添加员工";
      const res = await dept.listDept(this.queryParams);
      if(res.data.code === '000'){
        this.deptOptions = res.data.data
      }
    },
    //保存用户
    async saveUser(){
      const res=await dept.saveDeptRelationUser(this.formAddUser);
      if(res.data.code==='000'){
        this.addUserVisible=false,
        this.$message({
          message: '保存成功',
          type: 'success'
        }),
        this.getPage()//请求刷新，重新刷新页面
      }else{
        this.$message.error('保存失败');        
      }
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.departmentId,
        label: node.departmentName,
        children: node.children
      };
    },
    handleSelect(item) {
      this.formAddUser.username = item.username
      this.formAddUser.userId = item.userId
      this.formAddUser.personName = item.personName         
    },
    async queryUserByUsername(username,cb){
      const res = await user.queryUserByUsername({username:username})
      if(res.data.code === '000'){
        let arr = res.data.data
        if( res.data.data == undefined){
          cb(arr);
        }else {
          arr.forEach( item =>{
            item.value = item.personName
          })
          setTimeout(() => {
            cb(arr);
          }, 1000);
        }


      }
    },

    //根据客户名称和客户类别模糊查询
    async queryCustomerByCusNameAndCusType(){
      const res=await dept.getList(this.queryCustomer);
      if(res.data.code==='000'){
          this.tableData=res.data.data.records;
          this.total=res.data.data.total;
      }      
    },
    //多选框选中状态,将id转换成一个字符串
    handleSelectionChange(val){
      this.customerIdsArray=val;
      const idList = [];
      for (const v of this.customerIdsArray) {
        idList.push(v.customerId)
      };
      this.customerIds=idList.join(',');
    },
    //点击批量删除按钮
    async removeAllSelection() {
      if (this.customerIds.length > 0) {
        this.$confirm('此操作将删除选中项,是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          dept.deleteCustomerByIds({customerIds:this.customerIds}).then(res =>{
            if(res.data.code ==='000'){
              this.getPage(),
              this.$message({
              message: '删除成功',
              type: 'success'
              })
            }else{
              this.$message.error('删除失败');    
            }
          })
        }).catch(() => {
          
        })
      } else {
        this.$notify({
          title: '提示',
          message: '请勾选要提交的项！',
          type: 'warning',
          duration: 2000
        })
      }
    },
    //查询客户详情
    async checkCustomer(departmentId){
      this.checkCustomerVisible=true;
      const res=await dept.selectCustomerById({departmentId:departmentId});
      if(res.data.code==='000'){
        this.cheakCustomerData=res.data.data;
      }
    },
    //查出要修改的客户的数据
    async updateCustomerDialog(departmentId){
      this.updateCustomerVisible=true;
      const res=await dept.selectCustomerById({departmentId:departmentId});
      if(res.data.code ==='000'){
        this.updateCustomerData=res.data.data;
      }
    },
    //发起修改请求 
    async updateCustomer(){
      const res=await dept.updateCustomer(this.updateCustomerData);   
      if(res.data.code==='000'){
        this.updateCustomerVisible=false;
        this.$message({
          message: '修改成功',
          type: 'success'
        }),
        this.getPage()//请求刷新，重新刷新页面
      }else{
        this.$message.error("修改失败");
      }
    },
    //导出文件
    async exportCustomer(){
      const res=await dept.exportCustomer(this.formSearch);
      if(res.data.code==='000'){
        this.exportCustomerUrl=res.data.data;
        // window.open(this.exportCustomerUrl).then(()=>{

        // })
        this.download(this.exportCustomerUrl);
        this.$message({
          message: '导出成功',
          type: 'success'
        })
      }
    },
    //下载
    download(url){
      var iframe = document.createElement('iframe')
      iframe.style.display = 'none'
      iframe.src = url
      document.body.appendChild(iframe)
    },
    //导出选择的文件
    exportSelectCustomer(){
      if (this.customerIds.length > 0) {
        this.$confirm('此操作将导出选中项,是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          dept.exportSelectCustomer({customerIds:this.customerIds})
          .then(res =>{
            this.exportCustomerUrl=res.data.data;
            this.download(this.exportCustomerUrl);
            if(res.code='000'){
              this.$message({
              message: '导出成功',
              type: 'success'
              })
            }else{
              this.$message.error('导出失败');    
            }
          })
        }).catch(() => {
          this.$message.error('导出失败');
        })
      } else {
        this.$notify({
          title: '提示',
          message: '请勾选要导出的项！',
          type: 'warning',
          duration: 2000
        })
      }
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.formSearch.departmentId = data.departmentId
      this.departmentByUser(this.formSearch);
    },
    //查询部门员工
    async departmentByUser(data){
      const res = await dept.departmentByUser(data);
      if(res.data.code === '000' ){
          this.tableData=res.data.data.records;
          this.total=res.data.data.total;
      }
      
    },
    /** 查询部门列表 */
    async getList() {
      const res = await dept.listDept(this.queryParams);
      if(res.data.code === '000'){
        this.departmentData = res.data.data
      }
    },
    //过滤数据
    filterNode(value, data) {
      if (!value) return true;
      return data.departmentName.indexOf(value) !== -1;
    }
  }
}


</script>

<style>

.el-tree{
  margin-top: 20px;
}
</style>
